# Copyright (c) 2025 Huawei Technologies Co., Ltd.
# openUBMC is licensed under Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#         http://license.coscl.org.cn/MulanPSL2
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
# See the Mulan PSL v2 for more details.
import os
from conans import ConanFile, tools, AutoToolsBuildEnvironment

class BusyboxConan(ConanFile):
    name = "busybox"
    description = "The Swiss Army Knife of Embedded Linux"
    topics = ("conan", "tools", "busybox")
    license = "GPL-2.0-or-later"
    homepage = "https://busybox.net/"
    url = "https://github.com/conan-io/conan-center-index"
    settings = "os", "arch", "compiler", "build_type"
    exports_sources = ["permissions.ini", "services/telnetd.service"]

    options = {
        "shared": [True, False],
        "fPIC": [True, False]
    }
    default_options = {
        "shared": False,
        "fPIC": True
    }
    _autotools = None

    def configure(self):
        del self.settings.compiler.cppstd
        del self.settings.compiler.libcxx
        if self.options.shared:
            del self.options.fPIC

    def source(self):
        tools.get(**self.conan_data["sources"][self.version], strip_root=True)

    def _configure_autotools(self):
        if self._autotools:
            return self._autotools
        self._autotools = AutoToolsBuildEnvironment(self)
        return self._autotools

    def build(self):
        if self.settings.arch == "x86_64":
            return
        autotools = self._configure_autotools()
        chost = os.environ.get("CHOST")
        if chost:
            os.environ["CROSS_COMPILE"] = chost + "-"
        autotools.make(target="defconfig")
        autotools.make()

    def package(self):
        if self.settings.arch == "x86_64":
            return
        self.copy("busybox", dst="opt/debug")
        self.copy("permissions.ini")
        self.copy("*.service", src="services", dst="lib/systemd/system/")
        os.chdir(self.package_folder)
        os.makedirs("etc/systemd/system/multi-user.target.wants")
        self.run("ln -sf ../../../../lib/systemd/system/telnetd.service etc/systemd/system/multi-user.target.wants/telnetd.service")
